<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- <div >接收count值：{{$store.state.count}}</div> 
    <div><button @click="$store.commit('add',10)">+</button></div>
    <div><button @click="$store.commit('reduce')">-</button></div>-->

   <div> -------------  同步  mapMutations  -----------</div>
    <div >接收count值：{{count}}</div>
    <div><button @click="add(10)">+</button></div>
    <div><button @click="reduce">-</button></div>

    <div> ------------- 异步  mapActions  -----------</div>
    <div >接收count值：{{count}}</div> 
    <div><button @click="addAction(10)">+</button></div>
    <div><button @click="reduceAction">-</button></div>

  </div>
  
</template>

<script>
// 1.导入store
import store from '@/vuex/store'
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex' //注意这种写法，多行写时也要用大括号包裹

export default {
  name: 'count',
  data () {
    return {
      msg: 'Welcome to count page'
    }
  },
  // 2.引入store
  store,
  computed:{
      ...mapState(["count"]),   // （...）对象的扩展运算符
      ...mapGetters(["count"]), // 无论任何方法调用，在输出count之前（含初始化），都会调用getters里的方法
      // count(){
      //   return this.$store.getters.count;
      // },
    
      // products(){
      //   return this.$store.state.products
      // },

  },
  // methods:mapMutations(["add","reduce"]),
  methods:{
     ...mapMutations(["add","reduce"]),
  
    //...mapActions(["addAction","reduceAction"]),
    addAction:function(){
      return this.$store.dispatch('addAction');    // dispatch分发store.js里actions方法 addAction
    },
    reduceAction:function(){
      return this.$store.dispatch('reduceAction');  // dispatch分发store.js里actions方法 reduceAction
    },
  },
  //监控count值
  // watch:{
  //   count:function(newVal,oldVal){
  //     console.log('new值为:'+newVal)
  //     console.log('old值为:'+oldVal)
  //   }
  // },
  beforeCreate: function () {
      console.log('1-beforeCreate 初始化之前');
  },
  created: function () {
  console.log('2-created 创建完成');
  },
  beforeMount: function () {
  console.log('3-beforeMount 挂载之前');
  },
  mounted: function () {
  console.log('4-mounted 挂载之后');
  },
  beforeUpdate: function () {
  console.log('5-beforeUpdate 数据更新前');
  },
  updated: function () {
  console.log('6-updated 被更新后');
  },
  activated: function () {
  console.log('7-activated');
  },
  deactivated: function () {
  console.log('8-deactivated');
  },
  beforeDestroy: function () {
  console.log('9-beforeDestroy 销毁之前');
  },
  destroyed: function () {
  console.log('10-destroyed 销毁之后')
  }
  
}

//或者用实例的方式 监控
// app.$watch('count',function(newVal,oldVal){
//   console.log('用实例的方式')
// });

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
